<?php

namespace App\Http\Controllers\Manager;

use App\Events\ManagerMoneyChangeEvent;
use App\Http\Controllers\Controller;
use App\Models\AuthSingle;
//use App\Models\ServerEngine;
use App\Models\AuthSingleLog;
use DateInterval;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthSingleController extends Controller
{
    public $prefix='manager.singleEngine';

    public function index(){
        return view($this->prefix.'.index');
    }

    public function list(){
        $user=Auth::user();
        $list=$user->singleAuths;
        return ['list'=>$list];

    }

    public function add(Request $request){

        $info=$request->post('info');
        $item=new AuthSingle();
        $item->user_id=Auth::id();
        $item->guid=time().$item->user_id.$this->v4_UUID();
        $item->info=$info;
//        $item->endTime = date("Y-m-d H:m:s",strtotime("+3 days"));
        $item->endTime = date("Y-m-d H:m:s");
        $item->save();

        return $item;
    }
    public function del(Request $request){
        $id=$request->get('id');
        $item=AuthSingle::find($id);

        if ($item && $item->user_id==Auth::id()){
            $item->delete();
            return 1;
        }else{
            return -1;
        }
    }

    public function addtime(Request $request){
        $id=$request->get('id');
        $item=AuthSingle::find($id);

        if (strtotime($item->endTime)-time()>30*24*60*60){
            return ['err'=>1,'msg'=>'优惠期间，超过30天不可续费'];
        }

        $price=env('single_price',1);
        $user=Auth::user();
        if ($price>0){
            if ($user->remain_money<$price){
                return ['err'=>1,'msg'=>'积分不足'];
            }
            $user->remain_money-=$price;
            $user->save();
            event(new ManagerMoneyChangeEvent($user->id,0, 0,10,2,$price,0,$user->remain_money,'续费独立版授权时间'));
        }

        $baseDate=now(); //当前时间上添加
        if ($item->endTime && $item->endTime > now()) {
            $baseDate=date_create($item->endTime); //原有时间上添加
        }
        $di=DateInterval::createFromDateString('1 months');
        $newDate=date_add($baseDate,$di);
        $item->endTime=$newDate->format('Y-m-d H:i:s');
        $item->timestamps = false;
        $item->save();

        return ['err'=>0,'data'=>$item];
    }

    function clearIP(Request $request){
        $id=$request->get('id');
        $item=AuthSingle::find($id);
        if (time() - strtotime($item->updated_at) < 30*24*60*60){
            return ['err'=>1,'msg'=>'上次解绑时间：'.$item->updated_at.'，不足30天'];
        }
        $item->ip = null;
        $item->save();
        return ['err'=>0,'data'=>$item];
    }


    public function info(Request $request)
    {
        $code=$request->query('code');
        $time=$request->query('time');
        $sign=$request->query('sign');

        //检测参数是否为空
        if ($code=="" || $time=="" || $sign==""){
            return ["code"=>1,"data"=>["cur"=>0,"end"=>0],"msg"=>"参数错误"];
        }
        //检测code是否正确
        $as=AuthSingle::where('guid',$code)->first();
        if (!$as){
            return ["code"=>1,"data"=>["cur"=>0,"end"=>0],"msg"=>"授权码错误"];
        }
        //检测签名 code+key+time
        $sign_my=md5($code."y1FK3AvL76HJKdnQEW6".$time);
        if ($sign_my !==$sign){
            return ["code"=>1,"data"=>["cur"=>0,"end"=>0],"msg"=>"签名错误"];
        }

        if ($as->status==0){
            return ["code"=>1,"data"=>["cur"=>0,"end"=>0],"msg"=>"授权被禁用"];
        }

        $ip=$_SERVER["REMOTE_ADDR"];

        if ($as->status==1) {
            if (!$as->ip) {
                $as->ip = $ip;
                $as->save();
            } else {
                if ($as->ip !== $ip) {
                    return ["code" => 1, "data" => ["cur" => 0, "end" => 0], "msg" => "非法IP请求"];
                }
            }
        }

        $asl=new AuthSingleLog();
        $asl->auth_id=$as->id;
        $asl->ip=$ip;
        $asl->save();

        return ["code"=>0,"data"=>["cur"=>time(),"end"=> strtotime($as->endTime)],"msg"=>""];
    }


    function v4_UUID() {
        return sprintf('%04x%04x%04x%04x%04x%04x%04x%04x',
            // 32 bits for the time_low
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            // 16 bits for the time_mid
            mt_rand(0, 0xffff),
            // 16 bits for the time_hi,
            mt_rand(0, 0x0fff) | 0x4000,

            // 8 bits and 16 bits for the clk_seq_hi_res,
            // 8 bits for the clk_seq_low,
            mt_rand(0, 0x3fff) | 0x8000,
            // 48 bits for the node
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
    }

}
